<template>
  <div class="gap-col-8">
    <TagSwiper
      class="px-4"
      v-model="proxyTab"
      :items="searchResultTags"
      @click="(item) => setCurrentTab(item.value)"
    ></TagSwiper>
    <keep-alive>
      <component :is="currentComponent"></component>
    </keep-alive>
  </div>
  <Jsonld :schema="schema"></Jsonld>
</template>
<script setup>
import { computed, onActivated, onMounted, onUnmounted, shallowRef, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useSearchResultStore, useSearchStore } from '@/store/search'
import { toDate } from '@/utils/string-helper'
import Jsonld from '@/components/common/Jsonld.vue'
import TagSwiper from '@/components/common/TagSwiper.vue'
import { useNavRefresh } from '@/compositions/nav/refresh'
import { NAVS, SEARCH_RESULT_TYPE, SEARCH_RESULT_MAP as typeMap } from '@/constant'

const searchStore = useSearchStore()
const { updateViewerRouterOriginPath } = searchStore

const searchResultStore = useSearchResultStore()
const { currentTab, currentComponent, searchText } = storeToRefs(searchResultStore)
const { result, setCurrentTab: $setCurrentTab, searchResultTags, clearSearch } = searchResultStore
const proxyTab = computed(() => currentTab.value)

function setCurrentTab(v) {
  $setCurrentTab(v).then(updateViewerRouterOriginPath)
}

onMounted(() => {
  const route = useRoute()
  const type = route.query?.type
  const key = type ? Number(Object.keys(typeMap).find((key) => typeMap[key] === type)) : SEARCH_RESULT_TYPE.ALL
  setCurrentTab(key)
})
onUnmounted(() => setCurrentTab(null))
onActivated(() => requestAnimationFrame(() => setCurrentTab(currentTab.value))) // 必須先讓 SearchMain 完成 updateViewerRouterOriginPath，不然路徑會錯亂

useNavRefresh(NAVS.SEARCH, () => {
  clearSearch()
})

// Jsonld 佈置
const schema = shallowRef(null)
watchEffect(() => {
  schema.value = {
    '@context': 'https://schema.org',
    '@type': 'SearchResultsPage',
    name: `Search results for ${searchText.value}`,
    description: `Search results for ${searchText.value} on Fantasi`,
    mainEntity: [
      {
        '@type': 'ItemList',
        name: 'Creators',
        itemListElement: result.creator.map((v, i) => ({
          '@type': 'Person',
          position: i + 1,
          name: v.nickname,
          alternateName: v.username,
          identifier: `${v.aff}`,
          url: v.share_url,
          image: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
        })),
      },
      {
        '@type': 'ItemList',
        name: 'Videos',
        itemListElement: result.video.map((v, i) => ({
          '@type': 'VideoObject',
          position: i + 1,
          name: v.content,
          thumbnailUrl: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
          uploadDate: toDate(v.display_at).toISOString(),
          duration: v.video_time,
          contentUrl: v.share_url.replace(/\?share_aff=\d*/, ''),
          interactionStatistic: {
            '@type': 'InteractionCounter',
            interactionType: 'https://schema.org/LikeAction',
            userInteractionCount: v.like,
          },
          author: {
            '@type': 'Person',
            name: v.author.nickname,
            alternateName: v.author.username,
            identifier: `${v.author.aff}`,
          },
          publisher: {
            '@type': 'Organization',
            name: 'Fantasi',
            logo: {
              '@type': 'ImageObject',
              url: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
            },
          },
        })),
      },
      {
        '@type': 'ItemList',
        name: 'Images',
        itemListElement: result.image.map((v, i) => ({
          '@type': 'ImageObject',
          position: i + 1,
          name: v.content,
          thumbnailUrl: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
          uploadDate: toDate(v.display_at).toISOString(),
          contentUrl: v.share_url.replace(/\?share_aff=\d*/, ''),
          interactionStatistic: {
            '@type': 'InteractionCounter',
            interactionType: 'https://schema.org/LikeAction',
            userInteractionCount: v.like,
          },
          author: {
            '@type': 'Person',
            name: v.author.nickname,
            alternateName: v.author.username,
            identifier: `${v.author.aff}`,
          },
          publisher: {
            '@type': 'Organization',
            name: 'Fantasi',
            logo: {
              '@type': 'ImageObject',
              url: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
            },
          },
        })),
      },
      // {
      //   '@type': 'ItemList',
      //   name: 'Tags',
      //   itemListElement: [
      //     {
      //       '@type': 'Thing',
      //       position: 1,
      //       name: '{tag_name_1}',
      //       url: 'https://www.fantasi.one/tag/{tag_name_1}',
      //     },
      //     {
      //       '@type': 'Thing',
      //       position: 2,
      //       name: '{tag_name_2}',
      //       url: 'https://www.fantasi.one/tag/{tag_name_2}',
      //     },
      //   ],
      // },
    ],
  }
})
</script>
<style scoped lang="scss">
.tag-container {
  position: relative;
  width: 100%;

  .scroll {
    display: flex;
    width: 100%;
    max-width: 100%;
    overflow-x: auto;
  }

  .arrow {
    position: absolute;
    z-index: 50;
    top: 0;

    display: flex;
    justify-content: center;
    align-items: center;

    width: calc(2rem + 2px);
    height: 100%;

    border-radius: 1.875rem 0rem 0rem 1.875rem;
    background: rgba(24, 25, 37, 0.5);

    backdrop-filter: blur(9px);

    cursor: pointer;

    &-left {
      left: 0;
      border-radius: 0px 30px 30px 0px;
    }

    &-right {
      right: 0;
      border-radius: 30px 0px 0px 30px;
    }
  }
}
</style>
